//
//  TouSuHuoZhuViewController.m
//  Rabbit
//
//  Created 网络货运PRO版 on 2019/12/19.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "TouSuHuoZhuViewController.h"
#import "TZImagePickerController.h"
#import "ZXCollectionCell.h"
#import "STPickerView.h"
#import "STPickerSingle.h"

@interface TouSuHuoZhuViewController ()<AMapLocationManagerDelegate,TZImagePickerControllerDelegate,ZXCollectionCellDelegate, UICollectionViewDataSource,UICollectionViewDelegate, STPickerSingleDelegate>
{
    NSString *_tousuDate;
    NSString *_longitude;
    NSString *_latitude;
    NSString *_detailAddress;
    NSString *_abnormalType;//投诉原因
}
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic,strong) NSMutableArray *imageArr;
@property (nonatomic,strong) NSMutableArray *imageUrlArray;
@property (strong , nonatomic)NSMutableArray *complaintsReasonArray;
@property (strong , nonatomic)NSMutableArray *complaintsReasonModelArray;
@property (nonatomic,strong) UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UILabel *tousuReasonText;
@property (weak, nonatomic) IBOutlet UITextField *tousuReasonTextField;
@property (weak, nonatomic) IBOutlet UIButton *dateButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) IBOutlet UIButton *reasonButton;
@property (weak, nonatomic) IBOutlet UILabel *tipTextLabel;
@property (weak, nonatomic) IBOutlet UIView *photoBgView;
@property (weak, nonatomic) IBOutlet UILabel *dateText;
@property (weak, nonatomic) IBOutlet UIView *line;
@property (weak, nonatomic) IBOutlet UIView *line2;
@property (weak, nonatomic) IBOutlet UILabel *complaintsText;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *touSuShuoMingTextTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topBgViewHeight;

@end

@implementation TouSuHuoZhuViewController


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = BackgroundColor;
    
    [self configLocationManager];
    
    [self baseSetUp];
    
    [self complaintsReasonDataListRequest];
}

- (void)baseSetUp {
    
    if (_pageState == 0) {
        self.navigationItem.title = @"投诉";
        _dateText.text = @"发生时间";
        [_saveButton setTitle:@"投诉" forState:UIControlStateNormal];
        
    } else {
        self.navigationItem.title = @"异常上报";
        _tousuReasonText.text = @"异常说明";
        _dateText.text = @"发生时间";
        [_saveButton setTitle:@"上报" forState:UIControlStateNormal];
        _complaintsText.hidden = YES;
        _reasonButton.hidden = YES;
        _topBgViewHeight.constant = 80;
        _touSuShuoMingTextTop.constant = 0;
        _tousuReasonTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写异常说明" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    }
    
    _tousuDate = @"";
    _longitude = @"";
    _latitude = @"";
    _detailAddress = @"";
    _abnormalType = @"";
    _tousuReasonText.textColor = Dark_TextColor;
    _dateText.textColor = Dark_TextColor;
    _complaintsText.textColor = Dark_TextColor;
    _line.backgroundColor = BackgroundColor;
    _line2.backgroundColor = BackgroundColor;
    [_reasonButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    [_dateButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    _tipTextLabel.textColor = Light_TextColor;
    cut(_saveButton, BTN_BORDER_RADIUS);

    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 60, ScreenW, _photoBgView.cy_height) collectionViewLayout:flowLayout];
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [_photoBgView addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //注册cell和ReusableView（相当于头部）
    [self.collectionView registerClass:[ZXCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    
}

- (IBAction)buttonTypeClick:(UIButton *)sender {
    WEAKSELF
    if (sender.tag == 10) {
        BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMDHMS];
        datePickerView.title = @"选择日期";
        datePickerView.isAutoSelect = NO;
        datePickerView.addToNow = NO; // 是否添加“至今”
        datePickerView.showToday = NO; // 是否显示“今天”
        datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
            NSLog(@"选择的值：%@", selectValue);
            
            [sender setTitle:selectValue forState:UIControlStateNormal];
            _tousuDate = selectValue;
        };
        // 3.显示
        [datePickerView show:self];
        
    } else if (sender.tag == 15) {
        
        STPickerSingle *pickerSingle = [[STPickerSingle alloc]init];
        pickerSingle.widthPickerComponent = ScreenW;
        [pickerSingle setArrayData:self.complaintsReasonArray];
        [pickerSingle setTitle:@"请选择投诉原因"];
        [pickerSingle setContentMode:STPickerContentModeBottom];
        [pickerSingle setDelegate:self];
        [pickerSingle show];
        
    } else if (sender.tag == 20) {
        
        if (_pageState == 0) {
            
            if ([DCSpeedy isBlankString:_tousuReasonTextField.text] == YES || [DCSpeedy isBlankString:_tousuDate] == YES || [DCSpeedy isBlankString:_abnormalType] == YES) {
                [XSInfoView showInfo:@"必填信息不能为空" onView:self.view];
                return;
            }
            
        } else {
            
            if ([DCSpeedy isBlankString:_tousuReasonTextField.text] == YES || [DCSpeedy isBlankString:_tousuDate] == YES) {
                [XSInfoView showInfo:@"必填信息不能为空" onView:self.view];
                return;
            }
        }
        
        
        NSString *arrStr = [self.imageUrlArray componentsJoinedByString:@","];

        NSDictionary *params = nil;
        NSString *urlString = @"";

        if (_pageState == 0) {
            //投诉
            params = @{
                @"orderDetailCode": _orderCode,
                @"abnormalImage": arrStr,
                @"abnormalRemark": _tousuReasonTextField.text,
                @"occurrenceTime" : _tousuDate,
                @"longitude": _longitude,
                @"latitude": _latitude,
                @"abnormalType": _abnormalType,
            };
            urlString = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], ORDER_DETAIL_ABNORMAL);
            
        } else {
            //异常上报
            params = @{
                @"orderDetailCode": _orderCode,
                @"sceneImg": arrStr,
                @"description": _tousuReasonTextField.text,
                @"happenTime" : _tousuDate,
                @"longitude": _longitude,
                @"latitude": _latitude,
                @"address": _detailAddress,
                @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            };
            urlString = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], TRANSPORT_ABNORMAL);
        }
        
        [HTTPManager postNetworkRequest: urlString withParameter:params withVC:self netName:self.navigationItem.title success:^(id response, NSString *msg) {
            
            [XSInfoView showInfo:msg onView:weakSelf.view];
            
            [KNotificationCenter postNotificationName:YUNDANCENTERLIST_REFRESH object:nil];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    }
}

#pragma mark -- STPickerSingleDelegate
- (void)pickerSingle:(STPickerSingle *)pickerSingle selectedTitle:(NSString *)selectedTitle {
    UIButton *btn = [self.view viewWithTag:15];
    [btn setTitle:selectedTitle forState:UIControlStateNormal];
    NSInteger index = [self.complaintsReasonArray indexOfObject:selectedTitle];
    _abnormalType = self.complaintsReasonModelArray[index][@"code"];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArr.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    ZXCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    if (!cell) {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    if (indexPath.item == 0) {
        cell.close.hidden = YES;
    } else {
       cell.close.hidden = NO;
    }
    cell.imgView.image = [self.imageArr objectAtIndex:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //边距占5*4=20 ，2个
    //图片为正方形，边长：(fDeviceWidth-20)/2-5-5 所以总高(fDeviceWidth-20)/2-5-5 +20+30+5+5 label高20 btn高30 边
    return CGSizeMake((ScreenW-20)/4, (ScreenW-20)/4);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 5, 5, 5);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    
    NSLog(@"选择%ld",indexPath.row);
    if (indexPath.item == 0) {
        
        if (self.imageArr.count == 10) {
            [XSInfoView showInfo:@"最多可上传9张图片" onView:self.view];
        } else {
            
            [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
            imagePickerVc.allowPickingVideo = NO;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                [weakSelf.imageArr addObjectsFromArray:photos];
                //            weakSelf.imageArr = [[weakSelf.imageArr reverseObjectEnumerator] allObjects];
                [weakSelf.collectionView reloadData];
                
                [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD) file:photos fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
                    
                    [weakSelf.imageUrlArray addObject:response[@"data"]];
                    
                } failure:^(NSInteger code, NSString *msg) {
                    
                }];
                
            }];
            imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:imagePickerVc animated:YES completion:nil];
            
        }
        
    } else {
        
        //查看
        HZPhotoBrowser *browser = [[HZPhotoBrowser alloc] init];
        browser.isFullWidthForLandScape = YES;
        browser.isNeedLandscape = YES;
        browser.currentImageIndex = (int)(indexPath.item-1);
        browser.imageArray = weakSelf.imageUrlArray;
        [browser show];
    }
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)moveImageBtnClick:(ZXCollectionCell *)aCell{
    NSIndexPath * indexPath = [self.collectionView indexPathForCell:aCell];
    NSLog(@"删除了第%ld个图片",indexPath.row);
    [self.imageArr removeObjectAtIndex:indexPath.row];
    [self.imageUrlArray removeObjectAtIndex:indexPath.row-1];
    [self.collectionView reloadData];
}
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置允许连续定位逆地理
    [self.locationManager setLocatingWithReGeocode:YES];
    
    [self.locationManager startUpdatingLocation];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
}

#pragma mark - AMapLocationManager Delegate

/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    _longitude = CJStringWithFormat(@"%f",location.coordinate.longitude);
    _latitude = CJStringWithFormat(@"%f",location.coordinate.latitude);

    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.longitude) forKey:LONGITUDE];
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.latitude) forKey:LATITUDE];
    
    //详细信息
    if (reGeocode)
    {
        DebugLog(@"reGeocode:%@", reGeocode);
        _detailAddress = reGeocode.formattedAddress;
    }
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    
    DebugLog(@"定位error：%@",error);
}
- (void)dealloc
{
    [self cleanUpAction];
}

#pragma mark -获取投诉原因数据字典
- (void)complaintsReasonDataListRequest {
    WEAKSELF
    
    NSDictionary *parmas = @{@"types": @"abnormalType",@"token":[UserDefaultUtil valueForKey:USER_TOKEN],};
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],DICT_LISTDICT) withParameter:parmas withVC:self netName:@"投诉原因" success:^(id response, NSString *msg) {
        
        if ([[response firstObject][@"dictList"] count] != 0) {
            self.complaintsReasonModelArray = [response firstObject][@"dictList"];
            [[response firstObject][@"dictList"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [weakSelf.complaintsReasonArray addObject:obj[@"name"]];
            }];
            
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (NSMutableArray *)imageArr {
    if (!_imageArr) {
        _imageArr = [[NSMutableArray alloc] initWithObjects:image(@"gcy_icon_add_photo"), nil];
    }
    return _imageArr;
}
- (NSMutableArray *)imageUrlArray {
    if (!_imageUrlArray) {
        _imageUrlArray = [[NSMutableArray alloc] init];
    }
    return _imageUrlArray;
}
- (NSMutableArray *)complaintsReasonArray {
    if (!_complaintsReasonArray) {
        _complaintsReasonArray = [[NSMutableArray alloc] init];
    }
    return _complaintsReasonArray;
}
- (NSMutableArray *)complaintsReasonModelArray {
    if (!_complaintsReasonModelArray) {
        _complaintsReasonModelArray = [[NSMutableArray alloc] init];
    }
    return _complaintsReasonModelArray;
}

@end
